from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib import auth
from django.contrib.auth.decorators import login_required

from .forms import LoginForm


@login_required(login_url='anjuleye:login')
def index(request):
    return render(request, "anjuleye/index.html",
                  {'data': '安居才能乐业', 'username': request.user.username})


def signup(request):
    # 注册用户
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            return HttpResponseRedirect(reverse('anjuleye:login'))
    else:
        form = UserCreationForm()
    context = {'form': form}
    return render(request, 'anjuleye/signup.html', context=context)


def login(request):
    # 登入
    default_next_url = reverse('anjuleye:index')
    next_url = request.GET.get('next', default_next_url)

    # 如果已经登入了，就直接跳转
    if request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect(next_url)
    else:
        form = LoginForm()
    context = {'form': form}
    return render(request, 'anjuleye/login.html', context=context)


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect(reverse('anjuleye:login'))
